

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "gfxconv.h"



void DumpPSDInfos(void){

	printf("%d layer(s)\n\n", image.nb_layers); // nombre de layers...

	int i;
	for (i = 0; i < image.nb_layers; i++){ // infos de chaque layer...
		printf(" * Layer %d : %s\n", i, image.layers[i].name);
		printf("  x=%d, y=%d\n", image.layers[i].x, image.layers[i].y);
		printf("  width=%d, height=%d\n", image.layers[i].width, image.layers[i].height);
		printf("  visibility=%d, opacity=%d\n\n", image.layers[i].visible, image.layers[i].opacity);
	}

}


u32 GetHotspotCoords(u32 i){
	u32 n;
	u32 size = image.layers[i].width*image.layers[i].height;
	for (n=0; n<size; n++){
		if ((image.layers[i].data[n]>>24) == 255){
			u16 x = n%image.layers[i].width;
			u16 y = (n-x)/image.layers[i].width;
			
			x += image.layers[i].x;
			y += image.layers[i].y;
			
			return (x<<16) | y;
		}
	}
	return 0; // jamais atteint en théorie...
}


s32 GetImageHotspot(u32 i){
	for (; i<image.nb_layers; i++){
		if (image.layers[i].type == TYPE_HOTSPOT){
			return i;
		}
	}
	return -1;	
}



void Convert(int argc, char** argv){
	
	//DumpPSDInfos(); // petit dump de test...
	
	FILE * outfile = fopen("out.gfx", "wb+");
	
	#define GLOBAL_HEADER_SIZE 10
	#define IMG_HEADER_SIZE 8
	#define HS_HEADER_SIZE 4
	#define CP_HEADER_SIZE 0
	
	u32 entete_images = GLOBAL_HEADER_SIZE;
	u32 entete_colinfos = entete_images + image.nb_images*IMG_HEADER_SIZE;
	u32 donnees_images = entete_colinfos + image.nb_colinfos*CP_HEADER_SIZE;
	
	// entête global...
	fwrite(&image.width, 2, 1, outfile);
	fwrite(&image.height, 2, 1, outfile);
	fwrite(&image.nb_images, 2, 1, outfile);
	fwrite(&image.nb_colinfos, 2, 1, outfile);
	u32 i;

	// entêtes images
	for (i=0; i<image.nb_layers; i++){
		if (image.layers[i].type == TYPE_IMAGE){
			fwrite(&image.layers[i].width, 2, 1, outfile);
			fwrite(&image.layers[i].height, 2, 1, outfile);
			
			s32 hotspot = GetImageHotspot(i);
			if (hotspot == -1) {
				u32 null = 0;
				fwrite(&null, 4, 1, outfile);
			}
			else {
				u32 coords = GetHotspotCoords(GetImageHotspot(i));
				fwrite(&coords, 4, 1, outfile);
			}	
			
			fwrite(&donnees_images, 4, 1, outfile);
			donnees_images += image.layers[i].height*image.layers[i].width*4;
		}
	}
	
	// entêtes colinfos
	for (i=0; i<image.nb_layers; i++){
		if (image.layers[i].type == TYPE_COLINFOS){
		}

	}
	
	// donnees images
	for (i=0; i<image.nb_layers; i++){
		if (image.layers[i].type == TYPE_IMAGE){
			u32 n, size = image.layers[i].height*image.layers[i].width;
			for (n=0; n<size; n++){
				u8 converted_r = (image.layers[i].data[n]&0xFF)*31/255;
				u8 converted_g = ((image.layers[i].data[n]>>8)&0xFF)*63/255;
				u8 converted_b = ((image.layers[i].data[n]>>16)&0xFF)*31/255;
				u16 color = XF_RGB(converted_r, converted_g, converted_b);
				fwrite(&color, 2, 1, outfile);
				
				u8 alpha = (image.layers[i].data[n]>>24)*63/255;
				fwrite(&alpha, 1, 1, outfile);
			}
		}
	}

	//finito!
	fclose(outfile);
}


